import { useDialog } from '@/main'
import { IS_ELECTRON } from '@/store/useEnv'
import { $postMessage } from '@/utils/ipcRenderer'
import { getItem } from '@/utils/storage'
import { IpcRenderer } from 'electron'
import { onMounted } from 'vue'
import { useI18n } from 'vue-i18n'

let ipcRenderer: IpcRenderer
if (IS_ELECTRON) ipcRenderer = require('electron').ipcRenderer

export default () => {
  const { t } = useI18n()
  onMounted(() => {
    if (!IS_ELECTRON) return
    $postMessage(({ mainWin }) => {
      mainWin.on('close', e => {
        e.preventDefault()
        mainWin.show()
        mainWin.webContents.send('quit-app')
      })
    })

    ipcRenderer.on('quit-app', () => {
      const downloadingNums = getItem('downloadList')?.filter(item => item.status === 'downloading').length
      let content = t('confirm-quit-app')
      if (downloadingNums) content = `${downloadingNums + t('num-tasks-is-downloading')}`
      // useDialog().warning({
      //   title: t('confirm-quit-app'),
      //   content,
      //   positiveText: t('hidden-app'),
      //   negativeText: t('quit-app'),
      //   onPositiveClick: () => $postMessage(({ mainWin }) => mainWin.hide()),
      //   onNegativeClick: () => ipcRenderer.send('exit-app')
      // })
      useDialog().warning({
        title: t('confirm-quit-app'),
        content,
        positiveText: t('quit-app'),
        onPositiveClick: () => ipcRenderer.send('exit-app')
      })
    })
  })
}
